<template>
  <div>
    <el-main class="task-form" style="margin-bottom: 10px;">
      <el-form class="elForm">
      <el-form-item style="margin-bottom: 0">
          <el-date-picker
            v-model="form.start_end"
            type="daterange"
            :clearable="true"
            :shortcuts="shortcuts"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="search"
          />
        </el-form-item>
        <el-form-item class="mar-l-10" style="margin-bottom: 0">
          <el-input
            v-model="form.phone_number_search"
            placeholder="请输入手机编号"
            @change="search"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-select
          style="width: 180px;"
            class="mar-l-10"
            placeholder="请选择任务状态"
            v-model="form.status"
            clearable
             @change="search"
          >
            <template #prefix>
              <div class="select-prefix">任务状态：</div>
            </template>
            <el-option
              v-for="item in form.statusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="mar-l-10" style="margin-bottom: 0">
          <el-button type="primary" @click="search"> 查询 </el-button>
        </el-form-item>
          <el-button
            type="primary"
            style="margin-left: 10px"
            @click="taskClick"
            >创建任务
          </el-button>
          <!-- <el-button
            link
            style="margin-left: 10px"
            >
            <el-icon style="font-size: 30px;" @click="search"><Refresh /></el-icon>
          </el-button> -->
    </el-form>
    </el-main>
    <el-container>
      <el-main class="task-form">
        <div>
          <el-table
            :data="form.tableData"
            style="width: 100%"
            :header-cell-style="tableHeaderColor"

          >
          <el-table-column
              align="center"
              prop="id"
              label="ID"
            />
            <el-table-column
              align="center"
              prop="url"
              label="视频链接"
            />
            <el-table-column
              align="center"
              prop="phone_number"
              label="手机编号"
            />
            <el-table-column
              align="center"
              prop="status"
              label="状态"
            />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="changePage(scope.row)"
                  >查看评论列表
                </el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="TaskUpdate(scope.row)"
                  >更新评论
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="changePageDel(scope.row)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-block">
          <el-pagination
            background
            v-model:current-page="form.page"
            v-model:page-size="form.page_size"
            :page-sizes="[10, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="form.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
    <el-dialog
      :width="'500px'"
      v-model="form.taskVisible"
      title="创建任务"
      :close-on-click-modal="false"
      @close="taskHandler('cancel')"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="手机号" required>
          <el-select
            v-model="form.phone_number" placeholder="请选择手机号" size="large" style="width: 300px" >
      <el-option
        v-for="item in form.phoneList"
        :key="item.phone_number"
        :label="item.phone_number"
        :value="item.phone_number"
      />
    </el-select>
        </el-form-item>
        <el-form-item label="抖音链接" required>
          <el-input
            size="large"
            style="width: 300px; margin-right: 10px"
            v-model="form.url"
            placeholder="请输入抖音链接"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="position: relative">
          <span class="dialog-footer">
            <el-button @click="taskHandler('cancel')">取消</el-button>
            <el-button type="primary" @click="taskHandler('confirm')">
              确定
            </el-button>
          </span>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :width="'1200px'"
      v-model="form.commentsVisible"
      title="评论列表"
      :close-on-click-modal="false"
      @close="CommentsHandler('cancel')"
    >
<el-button
  type="primary"
  style="margin-left: 10px"
  @click="textClick(null)"
  >批量私信
</el-button>
<el-button
            link
            style="margin-left: 10px"
            >
            <el-icon style="font-size: 30px;" @click="searchComments"><Refresh /></el-icon>
          </el-button>
    <el-main class="task-form">
        <div>
          <el-table
            :data="form.tableDataComments"
            style="width: 100%"
            :header-cell-style="tableHeaderColor"
             @selection-change="handleSelectionChange"
          >
          <el-table-column type="selection" width="40" align="center"/>
          <el-table-column
              align="center"
              prop="id"
              label="ID"
            />
            <el-table-column
              align="center"
              prop="nickname"
              label="昵称"
            />
            <el-table-column
              align="center"
              prop="text"
              label="评论内容"
            />
            <el-table-column
              align="center"
              prop="reply_status"
              label="私聊状态"
            />
            <el-table-column
              align="center"
              prop="reply_text"
              label="私聊内容"
            />

            <el-table-column
              align="center"
              prop="create_time"
              label="抓取时间"
            />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  :disabled="scope.row.reply_status != '待处理'?true:false"
                  @click="textClick(scope.row)"
                  >私信
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-block">
          <el-pagination
            background
            v-model:current-page="form.page_comments"
            v-model:page-size="form.page_size_comments"
            :page-sizes="[10, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="form.total_comments"
            @size-change="handleSizeCommentsChange"
            @current-change="handleCurrentCommentsChange"
          />
        </div>
      </el-main>
  </el-dialog>
  <el-dialog
      :width="'800px'"
      v-model="form.textVisible"
      title="私信"
      :close-on-click-modal="false"
      @close="textHandler('cancel')"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="类型" required>
          <el-radio-group v-model="form.type">
            <el-radio :label="0" size="large">私信</el-radio>
            <el-radio :label="1" size="large">仅关注</el-radio>
            <el-radio :label="2" size="large">私信并关注</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回复内容" required v-if="form.type==0||form.type==2">
          <el-input
            size="large"
            style="width: 600px; margin-right: 10px"
            v-model="form.reply_text"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="position: relative">
          <span class="dialog-footer">
            <el-button @click="textHandler('cancel')">取消</el-button>
            <el-button type="primary" @click="textHandler('confirm')">
              确定
            </el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts"></script>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import { UploadFilled, Close,Refresh } from "@element-plus/icons-vue";
import { ElMessage, ElLoading,ElMessageBox  } from "element-plus";
import { UploadProps } from "element-plus";
import { useRouter } from "vue-router";
import { nextTick } from "process";
import moment from "moment";
import {
  getTaskCreate,
  getTaskList,
  getTaskDelete,
  getTaskUpdate
} from "@/api/task";
import {
  getTaskComments,
  getTaskCommentsUpdateReplyStatus,
} from "@/api/comments";
import {
  getPhoneList,
} from "@/api/phone";
const router = useRouter();
const { currentRoute } = router;
const shortcuts = [
  {
    text: "今天",
    value: () => {
      const end = new Date();
      const start = new Date();
      return [start, end];
    }
  },
  {
    text: "昨天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
      end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
      return [start, end];
    }
  },
  {
    text: "前天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
      end.setTime(end.getTime() - 3600 * 1000 * 24 * 2);
      return [start, end];
    }
  },
  {
    text: "最近三天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "最近七天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(1);
      return [start, end];
    }
  },
  {
    text: "上个月",
    value: () => {
      const start = new Date();
      start.setMonth(start.getMonth() - 1, 1);
      const end = new Date(start.getFullYear(), start.getMonth() + 1, 0);
      return [start, end];
    }
  }
];
const form = reactive({
  start_end:["",""],
  phone_number_search:"",
  status:"",
  statusList:[
    {id:"",name:"全部"},
    {id:"0",name:"待执行"},
    {id:"1",name:"进行中"},
    {id:"2",name:"完成"},
    {id:"3",name:"删除"},
  ],
  taskVisible: false,
  tableData: [],
  page: 1,
  page_size: 10,
  total: 0,
  phone_number: "",
  phoneList:[],
  url:"",
  tableDataComments:[],
  reply_text: "",
  type:0,
  ids:[],
  task_id:"",
  page_comments:1,
  page_size_comments:10,
  total_comments:0,
  textVisible:false,
  commentsVisible:false,
  multipleSelection:[]
});
const search = () => {
  form.page = 1;
  getDataList();
};
const searchComments=()=>{
  form.page_comments = 1;
  getCommentsDataList();
}
const handleSelectionChange = val => {
  form.multipleSelection = val
}
const dateFormat = (row, column) => {
  const date = row[column.property];

  if (date == undefined) {
    return "";
  }

  return moment(date * 1000).format("YYYY-MM-DD");
};
const TaskUpdate= async(val)=>{
  const res = await getTaskUpdate({
    status: 0,
    id: val.id,
  });
  if (res.code == 0) {
    getDataList();
    ElMessage({
            type: 'success',
            message:"更新成功",
          })
  }else{
          ElMessage({
            type: 'error',
            message: res.msg,
          })
        }
}
const changePage = (val) => {
    // const text = (window.location.origin + "/#/comments/").concat(
    //   val.id
    // );
    form.task_id=val.id;
    getCommentsDataList();
    form.commentsVisible=true;
    // console.log(text);
    // window.open(text, "_blank");
};
const changePageDel = (val) => {
  ElMessageBox.confirm(
    '确认删除该任务?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then( async() => {
      const res = await getTaskDelete({task_id:val.id});
      if (res.code == 0) {
          ElMessage({
            type: 'success',
            message:"删除成功",
          })
          getDataList();
        }else{
          ElMessage({
            type: 'error',
            message: res.msg,
          })
        }
    })
    .catch(() => {
    })
};
const getPhone = async () => {
  const res = await getPhoneList({
    page: 1,
    page_size:9999
  });
  if (res.code == 0) {
    form.phoneList = res.data.list;
  }
};
const taskClick = val => {
  form.taskVisible = true;
};
const taskHandler = async val => {
  if (val == "confirm") {
    if (form.phone_number == "") {
      return ElMessage.warning("请选择手机号");
    }
    if (form.url == "") {
      return ElMessage.warning("请输入抖音链接");
    }
    const res = await getTaskCreate({
      phone_number: form.phone_number,
      url:form.url
    });
    if (res.code == 0) {
      ElMessage.success("新增成功");
      form.page = 1;
      getDataList();
      form.phone_number = "";
      form.url="";
      form.taskVisible = false;
    }
  } else {
    form.phone_number = "";
    form.url="";
    form.taskVisible = false;
  }
};
const CommentsHandler =val=>{
  if (val == "cancel") {
    form.commentsVisible = false;
    form.tableDataComments = [];
    form.total_comments = 0;
  }
}
const handleSizeChange = val => {
  form.page_size = val;
  getDataList();
};
const handleCurrentChange = val => {
  form.page = val;
  getDataList();
};
const getDataList = async () => {
  let params={
    page: form.page,
    page_size: form.page_size,
    status: form.status,
  }
  if(form.start_end!=null){
    if(form.start_end[0]!=""){
    params.start_date=moment(form.start_end[0]).format("YYYY-MM-DD")
  }
  if(form.start_end[1]!=""){
    params.end_date=moment(form.start_end[1]).format("YYYY-MM-DD")
  }
  }
  if(form.phone_number_search!=""){
        params.phone_number=form.phone_number_search
  }
  const res = await getTaskList(params);
  if (res.code == 0) {
    form.tableData = res.data.list;
    form.total = res.data.total;
  }
};
const tableHeaderColor = data => {
  // console.log(data);
  if (data.rowIndex === 0) {
    return { background: "#f9f8fa", color: "#909399", textAlign: "center" };
  }
};
const textClick = val => {

   if(val!=null){
    form.textVisible = true;
    form.ids=[val.id]
   }else{
     if(form.multipleSelection.length==0){
      return ElMessage.warning("请选择评论");
     }
     form.textVisible = true;
     form.ids = form.multipleSelection.filter(item => item.reply_status === '待处理').map(item => item.id);
   }
};
const textHandler = async val => {
  if (val == "confirm") {
    if ((form.type==0||form.type==2)&&form.reply_text == "") {
      return ElMessage.warning("请输入回复内容");
    }
    let params={
      type: form.type,
      ids:form.ids
    }
    if(form.reply_text!=""){
       params.reply_text=form.reply_text
    }
    const res = await getTaskCommentsUpdateReplyStatus(params);
    if (res.code == 0) {
      ElMessage.success("操作成功");
      form.page = 1;
      getCommentsDataList();
      form.reply_text = "";
      form.multipleSelection=[];
      form.textVisible = false;
    }
  } else {
    form.reply_text = "";
    form.multipleSelection=[];
    form.textVisible = false;
  }
};
const handleSizeCommentsChange = val => {
  form.page_size_comments = val;
  getCommentsDataList();
};
const handleCurrentCommentsChange = val => {
  form.page_comments = val;
  getCommentsDataList();
};
const getCommentsDataList = async () => {
  const res = await getTaskComments({
    page: form.page_comments,
    page_size: form.page_size_comments,
    task_id:Number(form.task_id)
  });
  if (res.code == 0) {
    form.tableDataComments = res.data.list;
    form.total_comments = res.data.total;
  }
};
getDataList();
getPhone();
</script>
<style lang="scss" scoped>
.app-main {
  width: 100%;
  min-height: calc(100vh - 64px);
}

.task-form {
  background-color: #fff;
}

.pagination-block {
  display: flex;
  justify-content: right;
  margin: 20px 0 0;
}

.PasswordContent {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.elForm {
  display: flex;
  flex-wrap: wrap;
}
</style>
